package com.guoxin.part1.chapter8;

/**
 * 拒绝策略
 *
 * @author guoxin
 * @date 2019/8/29
 */
@FunctionalInterface
public interface DenyPolicy {

    /**
     * 拒接
     *
     * @param runnable   Runnable
     * @param threadPool ThreadPool
     */
    void reject(Runnable runnable, ThreadPool threadPool);

    /**
     * 该拒接策略会直接将任务丢弃
     */
    class DiscardDenyPolicy implements DenyPolicy {
        @Override
        public void reject(Runnable runnable, ThreadPool threadPool) {
            //TODO
        }
    }

    /**
     * 该拒绝策略会向任务提交者抛出异常
     */
    class AbortDenyPolicy implements DenyPolicy {
        @Override
        public void reject(Runnable runnable, ThreadPool threadPool) {
            throw new RunnableDenyException("The runnable " + runnable + " will be abort.");
        }
    }

    /**
     * 该拒接策略会使任务在提交者所在的线程中执行任务
     */
    class RunnerDenyPolicy implements DenyPolicy {
        @Override
        public void reject(Runnable runnable, ThreadPool threadPool) {
            if (!threadPool.isShutdown()) {
                runnable.run();
            }
        }
    }
}
